package top.kpromise.user.service_imp;

import org.springframework.stereotype.Service;
import top.kpromise.user.data.Config;
import top.kpromise.user.mapper.VerifyCodeMapper;
import top.kpromise.user.model.response.VerifyCodeModel;
import top.kpromise.user.response.Result;
import top.kpromise.user.service.VerifyCodeService;
import top.kpromise.user.utils.DateUtils;

import java.util.Date;
import java.util.Map;

@Service
public class VerifyCodeServiceImp implements VerifyCodeService {

    private final VerifyCodeMapper verifyCodeMapper;

    public VerifyCodeServiceImp(VerifyCodeMapper verifyCodeMapper) {
        this.verifyCodeMapper = verifyCodeMapper;
    }

    @Override
    public void saveCode(String receiver, String code, int type) {
        Date createdAt = DateUtils.currentDate();
        VerifyCodeModel verifyCodeModel = findCode(receiver, type);
        if (verifyCodeModel != null) {
            verifyCodeMapper.updateCode(receiver, type, code, createdAt);
        } else {
            verifyCodeMapper.saveCode(receiver, code, createdAt, type);
        }
    }

    @Override
    public VerifyCodeModel findCode(String receiver, int type) {
        return verifyCodeMapper.findCode(receiver, type);
    }

    @Override
    public void updateCode(String receiver, int type, String code, Date createAt) {
        verifyCodeMapper.updateCode(receiver, type, code, createAt);
    }

    @Override
    public void delete(String receiver, int type) {
        verifyCodeMapper.delete(receiver, type);
    }

    @Override
    public Map<String, Object> checkVerifyCode(String receiver, String verifyCode, int type) {
        int result = checkVerifyCodeInternal(receiver, verifyCode, type);
        if (result == Config.VerifyCodeStatus.notExists) {
            return Result.data(null, "请先获取验证码");
        }
        if (result == Config.VerifyCodeStatus.error) {
            return Result.data(null, "验证码错误");
        }
        if (result == Config.VerifyCodeStatus.timeout) {
            return Result.data(null, "验证码已过期");
        }
        return null;
    }

    private int checkVerifyCodeInternal(String receiver, String verifyCode, int type) {
        VerifyCodeModel verifyCodeModel = findCode(receiver, type);
        if (verifyCodeModel == null) return Config.VerifyCodeStatus.notExists;
        if (!verifyCode.equals(verifyCodeModel.getVerifyCode())) {
            return Config.VerifyCodeStatus.error;
        }
        long now = DateUtils.currentDate().getTime();
        Date created = DateUtils.currentDate(verifyCodeModel.getCreateAt());
        if (created == null) {
            return Config.VerifyCodeStatus.timeout;
        }
        long createdAt = created.getTime();
        if (now - createdAt > Config.SMS_TIME_OUT) {
            return Config.VerifyCodeStatus.timeout;
        }
        delete(verifyCodeModel.getReceiver(), type);
        return Config.VerifyCodeStatus.right;
    }
}
